package com.rent.message.rabbit;

import com.rent.common.constant.CommonConstant;
import com.rent.common.entity.HouseAuditMessageDto;
import com.rent.message.constant.MessageConstant;
import com.rent.message.pojo.entity.ChatMessage;
import com.rent.message.utils.BatchProcessorFactory;
import com.rent.message.utils.DistributedBatchProcessor;
import com.rent.message.ws.MessagePushService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class HouseAuditMq {

    @Autowired
    private BatchProcessorFactory batchProcessorFactory;

    @Autowired
    private MessagePushService messagePushService;


    private DistributedBatchProcessor<HouseAuditMessageDto> HouseAuditProcessor;




    /**
     * 初始化批量处理器
     */
    @PostConstruct
    public void init() {
        log.info("=== HouseAuditMq 初始化 ===");
        HouseAuditProcessor = batchProcessorFactory.getOrCreateProcessor(
                "house-audit-processor",
                100,
                10000L,
                this::sendToUser
        );

        log.info("=== HouseAuditMq 初始化完成，processor: {} ===", HouseAuditProcessor);
    }

    /**
     * 接收消息
     * @param message
     */
    @RabbitListener(queues = CommonConstant.QUEUE_HOUSE_AUDIT)
    public void receive(HouseAuditMessageDto message){
        log.info("=== 接收房源申请消息，开始处理 ===");
        log.info("申请内容: {}", message);
        try {
            HouseAuditProcessor.add(message);
            log.debug("接收房源申请消息，当前缓冲区大小: {}", HouseAuditProcessor.getBufferSize());
        } catch (Exception e) {
            log.error("处理房源申请消息失败: {}", message, e);
        }
    }

    private void sendToUser(List<HouseAuditMessageDto> messages) {
        if (messages.isEmpty()) {
            log.debug("房源申请消息为空");
            return;
        }

        try {
            for (HouseAuditMessageDto houseAuditMessageDto : messages){
                Map<String, Object> message = new HashMap<>();
                message.put("type", MessageConstant.MESSAGE_TYPE_HOUSE_AUDIT);
                message.put("title", "房源审核");
                message.put("content", houseAuditMessageDto.getTitle());
                message.put("status", houseAuditMessageDto.getAuditStatusName());
                message.put("time", houseAuditMessageDto.getAuditTime());
                messagePushService.sendNoticeToUser(houseAuditMessageDto.getLandlordId().toString(), message);
            }
        } catch (Exception e) {
            log.error("推送房源申请消息失败，数量: {}", messages.size(), e);
            throw new RuntimeException();
        }
    }



}
